from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
import json
from .models import User


def query_user_by_name(request):
    # name = request.GET['name'] # 获取GET请求参数 (不允许为空)
    name = request.GET.get('name')  # 获取GET请求参数 (允许为空)
    return HttpResponse(f"你正在找, {name}!")  # 返回响应


def user_detail(request, user_id):
    print(type(user_id))
    return HttpResponse(f"你正在查询user_id: {user_id} 的详情信息")  # 返回响应


def login(request):
    if request.method == 'GET':
        # 前往登录页面
        html_content = "<h2 style='color:blue'>欢迎来到登录页面</h2>"
        return render(request, 'login.html',context={"html_content": html_content})
    elif request.method == 'POST':
        # 处理登录请求
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(f"username: {username}, password: {password}")
        if username == 'admin' and password == '123456':
            return HttpResponseRedirect(reverse('home'))
        else:
            return HttpResponse("登录失败")
    else:
        return HttpResponse("<h1>不支持的请求方法</h1>")

def home(request):
    return render(request, 'home.html')

def register(request):
    if request.method == 'GET':
        # 前往注册页面
        return render(request, 'register.html')
    else:
        return HttpResponse("<h1>功能尚未开通</h1>")


def test_get_request_body(request):
    if request.method == 'POST':
        # 获取请求体
        request_body = request.body.decode('utf-8')
        data = json.loads(request_body)
        print(f"请求体：{data}")
        return HttpResponse(str(data),content_type="application/json",status=500)
    else:
        return HttpResponse("<h1>不支持的请求方法</h1>")



def add_user(request):
    name = request.POST.get('name')
    age = request.POST.get('age')
    phone = request.POST.get('phone')

    user = User(name=name, age=age, phone=phone)
    user.save()
    print(f"当前记录主键id:{user.pk}")
    return HttpResponse(f"用户添加成功，主键:{user.pk}，姓名:{user.name},年龄:{user.age},电话:{user.phone}")

def delete_user(request,id):
    try:
        user = User.objects.get(id=id)
        user.delete()
        return HttpResponse("用户删除成功")
    except User.DoesNotExist:
        print("用户不存在")
        return HttpResponse("用户不存在")

def update_user(request):
    id = request.POST.get('id')
    name = request.POST.get('name')
    age = request.POST.get('age')
    phone = request.POST.get('phone')
    try:
        user = User.objects.get(id=id)
        user.name = name
        user.age = age
        user.phone = phone
        user.save()
        return HttpResponse("修改成功")
    except User.DoesNotExist:
        print("用户不存在")
        return HttpResponse("用户不存在")

def query_all(request):
    # -字段 表示降序排列，字段表示升序排列
    users = User.objects.all().order_by('-id')
    user_list = []

    for temp in users:
        user = {}
        user['id'] = temp.pk
        user['name'] = temp.name
        user['age'] = temp.age
        user['phone'] = temp.phone
        user['time'] = temp.time.strftime('%Y-%m-%d %H:%M:%S')
        user_list.append(user)


    print(f"查询全部：{user_list}")
    return HttpResponse(f'查找全部：{user_list}')


def query_by_name(request):
    input_name = request.GET.get('name')
    # filter数据不存在不会报错
    users = User.objects.filter(name=input_name)

    user_list = []

    for temp in users:
        user = {}
        user['id'] = temp.pk
        user['name'] = temp.name
        user['age'] = temp.age
        user['phone'] = temp.phone
        user['time'] = temp.time.strftime('%Y-%m-%d %H:%M:%S')
        user_list.append(user)
    print(f"通过名字查询：{user_list}")
    return HttpResponse(f'通过名字查询：{user_list}')

def query_by_id(request,id):
    # get数据不存在会报错
    try:
        user = User.objects.get(id=id)
        user_dict = {}
        user_dict['id'] = user.pk
        user_dict['name'] = user.name
        user_dict['age'] = user.age
        user_dict['phone'] = user.phone
        user_dict['time'] = user.time.strftime('%Y-%m-%d %H:%M:%S')

        print(f"通过id查询：{user_dict}")
        return HttpResponse(f'通过id查询：{user_dict}')
    except User.DoesNotExist:
        print("用户不存在")
        return HttpResponse("用户不存在")
